package com.bawei.module_home.widget

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_common.entity.SendCommentBody
import com.bawei.lib_common.entity.VideoCommentEntityItem
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_home.R
import com.bawei.module_home.adapter.VideoCommentListAdapter
import com.bawei.module_home.databinding.DialogCommendListLayoutBinding
import com.bawei.module_home.intent.SimpleTypeIntent
import com.bawei.module_home.state.SimpleTypeState
import com.bawei.module_home.viewmodel.HomeViewModel
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

private const val TAG = "CommentDialog"
class CommentDialog constructor(private val itemId:String): DialogFragment() {
    private lateinit var mDataBinding: DialogCommendListLayoutBinding
    private lateinit var homeViewModel: HomeViewModel
    private val  commentList = mutableListOf<VideoCommentEntityItem>()
    private lateinit var commentListAdapter: VideoCommentListAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //设置样式
        setStyle(STYLE_NO_TITLE, R.style.BottomSheetDialog)
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.setCanceledOnTouchOutside(true)//设置外部区域可以取消
        dialog.window?.apply {
            setGravity(Gravity.BOTTOM)
            setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)//布局
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))//透明背景
        }
        return dialog
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mDataBinding =  DialogCommendListLayoutBinding.inflate(inflater, container, false)
        return mDataBinding.root
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
        updateUi()
        val close = view.findViewById<ImageView>(R.id.iv_list_close)
        val sendCom = view.findViewById<ImageView>(R.id.iv_commend_send)
        val content = view.findViewById<EditText>(R.id.et_commend_input)
        val uName = AuthMMKV.username
        val uId = AuthMMKV.uId
        close.setOnClickListener {
            dismiss()
        }
        sendCom.setOnClickListener {
           lifecycleScope.launch {
               repeatOnLifecycle(Lifecycle.State.STARTED){
                   homeViewModel.sendComment(SimpleTypeIntent.sendComment(SendCommentBody(
                       agreenum = 0,
                       content =  content.text.toString(),
                        createtime = getCurrentFormattedTime(),
                      datatype =  0,
                       id = 0,
                       itemid = itemId,
                       nickname = uName,
                       replytotal =  0,
                       userid = uId,
                       userlogo = "",
                       )))
               }
           }
            content.text = null
        }

    }

    private fun updateUi() {
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleCommentFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleVideoCommentSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            showVideoCommentList(it.list!!)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleSCommentFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleVideoCommentSendSuccess -> {
                            homeViewModel.intents.send(SimpleTypeIntent.getCommentByUserId(0,itemId))
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleDCommentFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleVideoCommentDeleteSuccess -> {
                            homeViewModel.intents.send(SimpleTypeIntent.getCommentByUserId(0,itemId))
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleYesLoveCommentFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleVideoCommentAgreeSuccess -> {
                            // 网络请求成功后，同步到本地数据库
                            val commentId = commentListAdapter.getCurrentClickedCommentId()
                            if (commentId != -1) {
//                                commentLikeManager.syncLikeData(commentId, AuthMMKV.uId, true)
                            }
                            homeViewModel.intents.send(SimpleTypeIntent.getCommentByUserId(0,itemId))
                            ToastUtils.showLong("点赞成功")
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleNOLoveCommentFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleVideoCommentCancelAgreeSuccess -> {
                            // 网络请求成功后，同步到本地数据库
                            val commentId = commentListAdapter.getCurrentClickedCommentId()
                            if (commentId != -1) {
//                                commentLikeManager.syncLikeData(commentId, AuthMMKV.uId, false)
                            }
                            homeViewModel.intents.send(SimpleTypeIntent.getCommentByUserId(0,itemId))
                            ToastUtils.showLong("取消点赞成功")
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }
    private fun showVideoCommentList(list: List<VideoCommentEntityItem>) {
        commentList.clear()
        commentList.addAll(list)
        commentListAdapter.notifyDataSetChanged()
    }
    private fun initData() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel.intents.send(SimpleTypeIntent.getCommentByUserId(0,itemId))
            }
        }
    }

    private fun initView() {
        commentListAdapter = VideoCommentListAdapter(commentList, onItemLongClick = {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED){
                    homeViewModel.intents.send(SimpleTypeIntent.deleteComment(commentList[it].id))
                }
            }
        }, onItemLoveClick = {
            val comment = commentList[it]
            val commentId = comment.id
            
            // 记录当前点击的评论ID，用于网络请求成功后同步
            commentListAdapter.setCurrentClickedCommentId(commentId)
            
            // 检查当前点赞状态
            lifecycleScope.launch {
//                val isCurrentlyLiked = commentLikeManager.isCommentLikedByUser(commentId, AuthMMKV.uId)
                
//                // 先更新本地数据库和UI
//                commentListAdapter.updateCommentLikeStatus(commentId, !isCurrentlyLiked)
//
//                // 发送网络请求
//                if (!isCurrentlyLiked){
//                    repeatOnLifecycle(Lifecycle.State.STARTED){
//                        homeViewModel.intents.send(SimpleTypeIntent.agreeComment(commentId))
//                    }
//                }else{
//                    repeatOnLifecycle(Lifecycle.State.STARTED){
//                        homeViewModel.intents.send(SimpleTypeIntent.cancelAgreeComment(commentId))
//                    }
//                }
            }
        })
        mDataBinding.commendList.expandList.setAdapter(commentListAdapter)
    }
    @RequiresApi(Build.VERSION_CODES.O)
    fun getCurrentFormattedTime(): String {
        // 获取当前时间（基于系统默认时区）
        val currentTime = LocalDateTime.now()

        // 定义格式化规则（yyyy=四位年，MM=两位月，dd=两位日，HH=24小时制小时，mm=分钟，ss=秒）
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

        // 格式化为目标字符串
        return currentTime.format(formatter)
    }
}